const HOST = require('../../config.js').host

var app = getApp()

Page({
  data: {
    circleList: [],//圆点数组
    awardList: [],//奖品数组
    colorCircleFirst: '#f69d7d',//圆点颜色1
    colorCircleSecond: '#ffffff',//圆点颜色2
    colorAwardDefault: '#F5F0FC',//奖品默认颜色
    colorAwardSelect: '#ffe400',//奖品选中颜色
    indexSelect: 0,//被选中的奖品index
    idxSelect:0,
    timeOut:960,
    isRunning: false,//是否正在抽奖
    resultType:"",
    userId:"",
    isShared:false,
    imageAward: [
      '../../assets/images/bazhe.png',
      '../../assets/images/wastLakeMenPiao.png',
      '../../assets/images/quqi.png',
      '../../assets/images/oufen.png',
      '../../assets/images/shouhuiMap.png',
      '../../assets/images/lvdougao.png',
      '../../assets/images/songchengMenPiao.png',
      '../../assets/images/mingxinpian.png',
    ],//奖品图片数组
    id:""
  },
  // 储存formId
  sendFormId(e) {
    console.log(e)
    wx.request({
      url: `${HOST}v1/formid/saveFormId`,
      method: 'POST',
      data: {
        userId: app.userId,
        formId: e.detail.formId
      },
      success: res => {
        console.log(res, '插入')
      }
    })
  },
  onShareAppMessage() {
    return {
      title: '赢好礼',
      path: '/pages/giftGame/giftGame',
      success:function(){
        console.log('转发成功')
      }
    }
  },
  onLoad(options) {
    console.log('companyKey:' + JSON.stringify(options))                                                     

    let self = this
    let isSharedArg = options.isSharedRederact;
    wx.login({
      success(res) {
        if (res.code) {
          wx.request({
            url: HOST + 'v1/login/' + res.code,
            method: 'GET',
            success(res) {
              if (res.data.sysCode === 1) {
                self.setData
                  ({
                    userId: res.data.data,
                  })
                
                if (isSharedArg == "true") {
                  self.setData
                    ({
                      isShared: true,
                    })
                }
                self.judgeIsLuckyDraw();
                self.saveScan(options);
                
              }
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    })
    // 统计扫码s


// 统计扫码e
  },
  //统计
  saveScan: function (options) {
    let self = this
    //获取id
    if (options.q) {
      let scanurl = options.q || "";
      let companyId =scanurl ? scanurl.match(/companyId%3D(\S*)%26companyKey/)[1] : "";
      let companyKey = scanurl ? scanurl.match(/companyKey%3D(\S*)/)[1] : "";
      console.log('companyId:' + companyId)
      console.log('companyKey:' + companyKey)
      console.log('URL:' + `${HOST}v1/qrcode/findByCompanyIdAndCompanyKey/${companyId}/${companyKey}`)

      //获取二维码id
      wx.request({
        url: `${HOST}v1/qrcode/findByCompanyIdAndCompanyKey/${companyId}/${companyKey}`,
        method: 'GET',
        success(res) {
          // console.log("res" + JSON.stringify(res));
          // console.log("res.data" + JSON.stringify(res.data));
          // console.log("res.data.data" + JSON.stringify(res.data.data));
          // console.log("res.data.data.id" + JSON.stringify(res.data.data.id));
          // console.log('userId:' + self.data.userId)
          // console.log('app.userId:' + app.userId)


          if (res.data.sysCode === 1) {
            let codeId = res.data.data.id
          // console.log('codeId:' + codeId)
          // console.log('findByCompanyIdAndCompanyId-->res.data.sysCode:' + res.data.sysCode)
            wx.request({
              url: HOST + 'v1/scanrecord/saveScanRecord',
              data: {
                userId: app.userId || self.data.userId,
                codeId: codeId,
                recordType: "A"
              },
              method: 'POST',
              success: function (res) {
                app.codeId = codeId
                // console.log('saveScanRecord-->res.data.sysCode:' + res.data.sysCode)
                // console.log('before-SUCCESS-->codeId:' + codeId)
                // console.log('before-SUCCESS-->app.userId:' + app.userId)

                if (res.data.sysCode === 1) {
                  // console.log('保存成功！')
                  // console.log('SUCCESS-->codeId:' + codeId)
                }
              },
              fail: function (res) {
                // console.log(JSON.stringify(res))
              }
            })
          }
        },
        fail: function () {
          self.saveScan(options);
        }
      })
    }else if(options.companyId){
      let companyId = options.companyId;
      let companyKey = options.companyKey;
      wx.request({
        url: `${HOST}v1/qrcode/findByCompanyIdAndCompanyKey/${companyId}/${companyKey}`,
        method: 'GET',
        success(res) {
        
          if (res.data.sysCode === 1) {
            let codeId = res.data.data.id
            
            wx.request({
              url: HOST + 'v1/scanrecord/saveScanRecord',
              data: {
                userId: app.userId || self.data.userId,
                codeId: codeId,
                recordType: "A"
              },
              method: 'POST',
              success: function (res) {
                app.codeId = codeId
               

                if (res.data.sysCode === 1) {
                
                }
              }
            })
          }
        },
        fail: function () {
          self.saveScan(options);
        }
      })
    }

  },
  //开始游戏
  startGame: function () {
    let that = this
    if (this.data.isRunning) return
    this.setData({
      isRunning: true
    })
    this.luckyDraw();
    var _this = this;
    var idxSelect = 0
    var i = 0;
    var timer = setInterval(function () {
      idxSelect++;
      //这里我只是简单粗暴用y=30*x+200函数做的处理.可根据自己的需求改变转盘速度
      i += 30;
      



      if (i == _this.data.timeOut) {
        console.log(i, _this.data.timeOut)
        //去除循环
        clearInterval(timer)
        //获奖提示

              _this.setData({
                // isRunning: false
              }) 
              setTimeout(function(){        
                wx.redirectTo({
                  url: `../giftDetail/giftDetail?prizeType=${_this.data.resultType}&id=${that.data.id}`,
              })},1400)
    
      }
      idxSelect = idxSelect % 8;
      _this.setData({
        idxSelect: idxSelect
      })
    }, (200))
  },



  judgeIsLuckyDraw() {
    let self = this;
    wx.request({
      url: HOST + 'v1/winrecord/checkIsHave/' + self.data.userId + "," + "1",
      method: 'GET',

      success: function (res) {
    
        if (res.data.sysCode === 1) {
          if (self.data.isShared) {
            self.setUserInterFace();            
          } else if(res.data.data === false){
            self.setUserInterFace();
          }
          else{
    
            let prizeType = "D";
            if (!self.data.isShared) {
              wx.redirectTo({
                url: `../giftDetail/giftDetail?prizeType=${prizeType}`,
              })
            }
            
          }
        }
      }
    })
  },

 setUserInterFace()
 {
   var _this = this;
   //圆点设置
   var leftCircle = 7.5;
   var topCircle = 7.5;
   var circleList = [];
   for (var i = 0; i < 24; i++) {
     if (i == 0) {
       topCircle = 15;
       leftCircle = 15;
     } else if (i < 6) {
       topCircle = 7.5;
       leftCircle = leftCircle + 102.5;
     } else if (i == 6) {
       topCircle = 15
       leftCircle = 620;
     } else if (i < 12) {
       topCircle = topCircle + 94;
       leftCircle = 620;
     } else if (i == 12) {
       topCircle = 565;
       leftCircle = 620;
     } else if (i < 18) {
       topCircle = 570;
       leftCircle = leftCircle - 102.5;
     } else if (i == 18) {
       topCircle = 565;
       leftCircle = 15;
     } else if (i < 24) {
       topCircle = topCircle - 94;
       leftCircle = 7.5;
     } else {
       return
     }
     circleList.push({ topCircle: topCircle, leftCircle: leftCircle });
   }
   this.setData({
     circleList: circleList
   })
   //圆点闪烁
   setInterval(function () {
     if (_this.data.colorCircleFirst == '#f69d7d') {
       _this.setData({
         colorCircleFirst: '#ffffff',
         colorCircleSecond: '#f69d7d',
       })
     } else {
       _this.setData({
         colorCircleFirst: '#f69d7d',
         colorCircleSecond: '#ffffff',
       })
     }
   }, 500)
   //奖品item设置
   var awardList = [];
   //间距,怎么顺眼怎么设置吧.
   var topAward = 25;
   var leftAward = 25;
   for (var j = 0; j < 8; j++) {
     if (j == 0) {
       topAward = 25;
       leftAward = 25;
     } else if (j < 3) {
       topAward = topAward;
       //166.6666是宽.15是间距.下同
       leftAward = leftAward + 166.6666 + 15;
     } else if (j < 5) {
       leftAward = leftAward;
       //150是高,15是间距,下同
       topAward = topAward + 150 + 15;
     } else if (j < 7) {
       leftAward = leftAward - 166.6666 - 15;
       topAward = topAward;
     } else if (j < 8) {
       leftAward = leftAward;
       topAward = topAward - 150 - 15;
     }
     var imageAward = this.data.imageAward[j];
     awardList.push({ topAward: topAward, leftAward: leftAward, imageAward: imageAward });
   }
   this.setData({
     awardList: awardList
   })
 },

 /**
  * 抽奖
  */
 luckyDraw() {
   let self = this;
   wx.request({
     url: HOST + 'v1/winrecord/saveWinRecord',
     method: 'POST',
     data: {
       userId: self.data.userId,
       activityId: "1"
     },
     success: function (res) {
        console.log(res)
       if (res.data.sysCode === 1) {
         if (res.data.data.resultType === "A") 
         {
           
           self.setData({
             indexSelect : 1,
             resultType : "A",
             timeOut:990,
             id:res.data.data.id
             })
         }
         else if (res.data.data.resultType === "C")
         {
           self.setData({
             indexSelect : 0,
             resultType:"C",
             timeOut:960,
             id: res.data.data.id
           })

         }
         else if (res.data.data.resultType === "B")
         {
           self.setData({
             indexSelect : 3,
             resultType:"B",
             timeOut: 1050,
             id: res.data.data.id
           })
         }
         else if (res.data.data.resultType === "G") {
           self.setData({
             indexSelect: 2,
             resultType: "G",
             timeOut: 1020,
             id: res.data.data.id
           })
         }
         else if (res.data.data.resultType === "F") {
           self.setData({
             indexSelect: 7,
             resultType: "F",
             timeOut: 1170,
             id: res.data.data.id
           })
         }
         else if (res.data.data.resultType === "E") {
           self.setData({
             indexSelect: 5,
             resultType: "E",
             timeOut: 1110,
             id: res.data.data.id
           })
         }
         else if (res.data.data.resultType === "H") {
           self.setData({
             indexSelect: 4,
             resultType: "H",
             timeOut: 1080,
             id: res.data.data.id
           })
         }
       }
     }
   })
 },
})
